<?php
namespace App\Admin\Models;
use Common\BaseModel;
use Common\Common;

class Wallets extends BaseModel
{
    protected $res;
    protected $redis_key = "wallets_";

    public function getSource()
    {
        return "f_wallets";
    }

    public function initialize()
    {
        parent::initialize();
    }

    public function amountAll($columns = 'amount')
    {
        $where['columns'] = "sum($columns) as amount";
        $amount           = $this->findFirst($where);
        return $amount->amount ? Common::number_randtwo($amount->amount) : 0;
    }

    /**
     * @func 根据用户id返回用户的余额信息
     * @param $uid 用户id
     * @return mixed 返回用户的余额信息
     */
    public function findbyUserId($uid)
    {
        $info = $this->findFirstByUserId($uid);
        if (!$info) {
            $this->user_id        = $uid;
            $this->settled        = 0;
            $this->amount         = 0;
            $this->gold           = 0;
            $this->yuanbao        = 0;
            $this->ad_amount      = 0;
            $this->withdrawing    = 0;
            $this->withdrawed     = 0;
            $this->created_at     = date('Y-m-d H:i:s');
            $this->updated_at     = date('Y-m-d H:i:s');
            $this->sms_money      = 0;
            $this->gold_money     = 0;
            $this->virtural_money = 0;
            $this->quqian_money   = 0;
            $this->red_amount     = 0;
            $this->save();
            $info = $this;
        }
        return $info;
    }


    public function myWallets($user_id)
    {
        $res = $this::findFirstByUserId($user_id);
        if (empty($res)) {
            return false;
        } else {
            return $res->toarray();
        }
    }

    public function findbyUserMoney($user_id)
    {
        $condition['conditions'] = "user_id = $user_id";
        $condition['columns']    = "amount";
        $res                     = $this->findFirst($condition);
        if ($res == false) {
            return 0;
        }
        return doubleval($res->amount);
    }

    public function upgold($user_id, $pond)
    {
        $res = $this->findFirstByUserId($user_id);
        if ($res) {
            if ($res->gold == null) {
                $res->gold = $pond;
            } else {
                $res->gold += $pond;
            }
            $res->save();
            return true;
        }
        return false;
    }

    public function exchange_gold($params)
    {
        $res['res'] = false;
        $user_info  = $this->findFirstByUserId($params['user_id']);
        //蓝宝石池
        $yuanbao_pone = 0;
        $luck         = 0;
        $gold         = doubleval($params['gold']);
        if ($gold < 1) {
            $res['msg'] = '最低1钻石起兑';
            return $res;
        }
        if ($gold > doubleval($user_info->gold)) {
            $res['msg'] = '钻石额度不足';
            return $res;
        }
//兑换现金
        if ($params['type'] == 'cash') {
            $user_info->amount += $gold * 0.8;
            $yuanbao_pone      = $gold * 0.2;
            $user_info->gold   -= $gold;
            $user_info->save();
        }
        if ($params['type'] == 'yuanbao') {
            if ($gold != 1) {
                $res['msg'] = '抽奖钻石只能为1';
                return $res;
            }
            $num = rand(1, 1001);
            if ($num <= 990) {
                $luck = 1;
            }
            if ($num <= 1000 && $num > 990) {
                $luck = 10;
            }
            if ($num == 1001) {
                $luck = 100;
            }
            $yuanbao_pone       = 1;
            $user_info->gold    -= 1;
            $user_info->yuanbao += $luck;
            $user_info->save();

        }
        $res['yuanbao_pone'] = $yuanbao_pone;
        $res['luck']         = $luck;
        $res['res']          = true;
        return $res;

    }

    public function sum_yuambao()
    {
        $condition['columns'] = 'sum(yuanbao) as yuanbao';
        $res                  = $this->findFirst($condition);
        return round(doubleval($res->yuanbao), 2);
    }

    public function exchange_yuanbao($price)
    {
        $condition['conditions'] = "yuanbao >0";
        $condition['limit']      = 100;
        $res                     = $this->find($condition);
        if ($res->toarray() != []) {
            foreach ($res as $k => $v) {
                $v->amount  += $v->yuanbao * $price;
                $v->yuanbao = 0;
                var_dump('需要分佣，日志');
                //$v->save();
                //日志
            }
            return false;
        }
        return true;
    }

    public function save_params($params)
    {
        return $this::save($params);
    }

    /**
     * @param $ServiceCharge 手续费
     * @param int $ratio 回收蓝宝石比例
     * @param int $jb_ratio 钻石蓝宝石比例
     * @return array
     */
//    public function compulsory_recovery($ServiceCharge, $ratio = 0, $jb_ratio = 20000, $is_manual = 0)
    public function compulsory_recovery($yuanbao, $ratio)
    {
        $condition['conditions'] = "yuanbao > 0";
        $res                     = $this->find($condition);
        $sm_num                  = 0;
        $dates                   = date('Y-m-d H:i:s');
        $batchList               = array();
        foreach ($res as $k => $v) {
            $temp['user_id']      = $v->user_id;
            $temp['changge_type'] = 'yuanbao_to_cach';
            $temp['old_coin']     = $v->amount;
            //强制回收 系统会以1元/蓝宝石强制回收50%，收取1%-10%手续费，用于给新会员购买//，老会员也可以持续买入，买入必须用钻石
            //有回收比例 按照比例回收
            $sm_yb = intval($v->yuanbao * ($yuanbao->ratio / 10000 - 1));
            if ($ratio > 0) {
                $sm_yb += intval($v->yuanbao * ($ratio / 100));
            }

            if ($sm_yb < 1) {
                continue;
            }
            $new_coin         = intval($sm_yb * (1 - $yuanbao->service_charge / 100));
            $yb['is_manual']  = 1;
            $temp['new_coin'] = $v->amount + $new_coin;
            $temp['date']     = $dates;

            $batchList[] = $temp;
            $sm_num      += $sm_yb;
        }

        if ($sm_num > 0) {
            $yb['yuanbao_num']        = $sm_num;
            $yb['ratio']              = $yuanbao->ratio;
            $yb['service_charge']     = $yuanbao->service_charge;
            $yb['oid_yuanbao_count']  = $yuanbao->fx_yb_num;
            $yb['oid_sm_yuanbao']     = $yuanbao->sm_yb_num;
            $yb['oid_yh_yuanbao']     = $yuanbao->yh_yb_num;
            $yb['this_yuanbao_count'] = $yuanbao->fx_yb_num + $sm_num;
            $yb['this_sm_yuanbao']    = $yuanbao->sm_yb_num + $sm_num;
            $yb['this_yh_yuanbao']    = $yuanbao->yh_yb_num;
            $yb['created_at']         = $dates;
            $logs                     = new YuanbaoRecoveryLog();
            $logs->save($yb);
            //写入日志
            $log = new AdMoneyExchangeLog();
            $log->batch_insert($batchList);
        }
        return $sm_num;
    }

    //批量更新钻石
    public function batch_update($updateStr, $updateId)
    {
        $updateSql = <<<ENT
UPDATE Wallets
    SET gold = CASE user_id
        $updateStr
    END
WHERE user_id IN ($updateId)
ENT;
        return $this->modelsManager->executeQuery($updateSql);
    }

    public function get_count_list($data)
    {
        $conditions = '';

        $page = isset($data['page']) ? $data['page'] : 1;
        $size = isset($data['limit']) ? $data['limit'] : 10;
        if ($page > 0) {
            $page = ($page - 1) * $size;
        }
        $result['count'] = $this::count();
        $result['list']  = $this::find(
            array(
                $conditions,
                "columns" => 'user_id',
                'limit'   => $size,
                'offset'  => $page,
                'order'   => 'amount ' . $data['sort'],
            ))->toarray();
        return $result;
    }

    public function get_amount()
    {
        $columns['column'] = 'amount';
        return $this::sum($columns);
    }

    public function sumNums($column = 'gold_money')
    {
        $columns['column'] = $column;
        return $this::sum($columns);
    }
}
